package cn.itsource.hrm.controller;

import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.util.FastDfsApiOpr;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author jinhui
 * @version V1.0.0
 * @date 2020/5/24
 */

@RestController
public class FileController {
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file){
        try {
            //获取文件内容
            byte[] bytes = file.getBytes();
            //获取文件真实名
            String filename = file.getOriginalFilename();
            //获取文件拓展名
            String extname = filename.substring(filename.lastIndexOf(".") + 1);
            String fileID = FastDfsApiOpr.upload(bytes, extname);


            return AjaxResult.me().setSuccess(true).setMessage("成功").setResultObj(fileID);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(true).setMessage("失败"+e.getMessage());
        }

    }
    //将模板下载
    @PostMapping("/download")
    public void download(@RequestParam("fileId") String fileId, HttpServletResponse response){
        //调用fastdfsAPI的下载方法
        try {
            String fileIdname = fileId.substring(fileId.indexOf("/")+ 1);
            String groupName = fileIdname.substring(0, fileIdname.indexOf("/"));
            String Filename=fileIdname.substring(fileIdname.indexOf("/")+1);
            //获取到文件内容
            byte[] bytes = FastDfsApiOpr.download(groupName, Filename);
            //将内容写出到响应对象的输出流
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

